<template>
  <div class="centermap">
    <div class="maptitle">
      <div class="zuo"></div>
      <span class="titletext">{{ maptitle }}</span>
      <div class="you"></div>
    </div>
    <div class="mapwrap">
      <dv-border-box-13 >
        <div class="ansexi" v-if="!blackOn" @click="setBlack('black')">
          暗色系
        </div>
        <div class="ansexi" v-if="blackOn" @click="setBlack('blackNo')">
          暖色系
        </div>
        <div class="quanguo" @click="addLayer95(url,params)">
          {{typeName}}
        </div>
        <div id="myMap" class="map-container">
        </div>
      </dv-border-box-13>
    </div>
  </div>
</template>

<script>
import Map from 'ol/Map.js';
import 'ol/ol.css';
import View from 'ol/View.js';
import Projection from "ol/proj/Projection";
import {transform,get,fromLonLat} from 'ol/proj';
import {Vector,ImageWMS,WMTS,XYZ} from 'ol/source';
import {Style, Stroke, Fill, Circle, Text, Icon} from 'ol/style';
import {MousePosition,ScaleLine,defaults,ZoomToExtent,FullScreen} from 'ol/control';
import {getWidth,getTopLeft} from 'ol/extent';
import WMTSGrid from 'ol/tilegrid/WMTS';
import TileGrid from 'ol/tilegrid/TileGrid';
import {Vector as VectorLayer,Image as ImageLayer,Tile} from 'ol/layer';
import {Vector as VectorSource,TileArcGISRest,OSM} from 'ol/source';
import GeoJSON from 'ol/format/GeoJSON';
import {DragBox, Select, defaults as defaultInteractions} from 'ol/interaction';
import axios from "axios";

export default {
  data() {
    return {
      map:null,
      bgLayer:null,
      blackOn:true,
      layer:null,
      maptitle: "智慧产业大脑",
      typeName:"空间现状",
      url:"http://218.93.116.192:8087/geoserver/xf/wms",
      params:{
        LAYERS: "xf:wjxzydfb2022"
      },
      mapInfoLayer:null,
      vectorSource:null
    };
  },
  created() { },

  mounted() {
    let that=this
    // that.initMap()
    that.initMapForArcgis()
    setTimeout(()=>{
      that.initQuJie()
      that.addLayer95(that.url,that.params)
    },500)
  },
  watch:{
    '$store.state.mapChangeData': function () {
      var that=this
      let data=that.$store.state.mapChangeData
      if (data.url===""){
        that.backMap()
        return
      }
      data.params.CQL_FILTER=null
      that.changeImageUrl(data.url,data.params)
      that.map.getView().setCenter(data.location)
      that.map.getView().setZoom(data.zoom)
      that.typeName=data.name
    },
  },
  methods: {
    backMap(){
      let that=this
      let data=that.$store.state.mapChangeData
      if (data.params.LAYERS===that.params.LAYERS){
        return
      }else {
        that.typeName="空间策略"
        that.url="http://218.93.116.192:8087/geoserver/xf/wms"
        that.params={
          LAYERS: "xf:wjxzydfb2022"
        }
        that.map.removeLayer(that.layer)
        that.layer=null
        that.addLayer95(that.url,that.params)
        that.map.getView().setZoom(10.7)
        that.map.getView().setCenter([119.90, 31.61])
      }
    },
    setBlack(msg){
      let that=this
      if (msg=='black'){
        that.bgLayer.getSource().setTileLoadFunction(
            function (imageTile, src) {
              that.myTileLoadFunction(imageTile, src)
            }
        )
        that.blackOn=true
      }else if (msg=='blackNo'){
        that.bgLayer.getSource().setTileLoadFunction(
            function (imageTile, src) {imageTile.getImage().src=src}
        )
        that.blackOn=false
      }
    },
    changeImageUrl(url,params){
      var that=this
      if (that.layer){
        that.layer.getSource().setUrl(url)
        that.layer.getSource().updateParams(params)
        return
      }else {
        that.addLayer95(that.url,params)
      }
    },
    addLayer95(url,params) {
      var that=this
      if (that.layer){
        that.map.removeLayer(that.layer)
        that.layer=null
        return
      }
      var image = new ImageLayer({
        source: new ImageWMS({
          //不能设置为0，否则地图不展示。
          ratio: 1,
          url: url,
          params: params,
          serverType: "geoserver",
        }),
      });
      var bounds = [119.40628051757812,31.102294921875,120.46096801757812,32.0416259765625];

      var projection = new Projection({
        code: 'EPSG:4326',
        units: 'degrees',
        axisOrientation: 'neu',
        global: false
      });
      var map =that.map
      that.layer=image
      map.addLayer(image)

    },
    initQuJie(){
      var that=this
      var map=that.map
      var func=function (feature) {
        return  new Style({
          fill: new Fill({
            color: 'rgba(0,0,0,0)'
          }),
          stroke: new Stroke({
            color: '#dea137',
            width: 1
          })
        })
      }
      var vectorSource = new VectorSource({
        features: null,
      })
      let qjLayer = new VectorLayer({
        source: vectorSource,
        style: func
      })
      map.addLayer(qjLayer)
      let instance = axios.create()
      let url="http://218.93.116.192:8089/party/static/BL.json"
      if (process.env.NODE_ENV == 'development') {
        url="/BL.json"
      }
      instance.get(url,{}).then((r)=>{
        if (r.status==200){
          var json=r.data
          var geoFormat=new GeoJSON()
          json.features.forEach(item=>{
            var feature=geoFormat.readFeature(item)
            vectorSource.addFeature(feature)
          })
          // map.getView().fit(vectorSource.getExtent(), map.getSize())
          map.getView().setZoom(10.7)
          map.getView().setCenter([119.90, 31.61])
        }
      })
    },
    initMap() {
      console.log("开始加载地图！")
      let that=this
      var map=null
      //定义投用信息
      var projection = new Projection({
        code: 'EPSG:4326',
        units: 'degrees',
        axisOrientation: 'neu'
      });
      var projection1 = get('EPSG:4326');
      var resolutions1 = new Array(18);
      var projectionExtent = projection1.getExtent();
      var matrixIds = new Array(18);
      var size = getWidth(projectionExtent) / 256;
      for (var z = 1; z < 19; ++z) {
        resolutions1[z] = size / Math.pow(2, z);
        matrixIds[z] = z;
      }
      var wmtsUrl_1 = 'https://t{0-7}.tianditu.gov.cn/vec_c/wmts?tk='; //矢量底图
      var webKey = "137c55da7638cc1eb357a0d41d99719d";
      var layer1 =new Tile({
        opacity: 1,
        source: new WMTS({
          url: wmtsUrl_1 + webKey,
          layer: 'vec',
          matrixSet: 'c',
          format: 'tiles',
          style: 'default',
          projection: projection1,
          tileGrid: new WMTSGrid({
            origin: getTopLeft(projectionExtent),
            resolutions: resolutions1,
            matrixIds: matrixIds
          }),
          wrapX: true,
          tileLoadFunction: function (imageTile, src) {
            that.myTileLoadFunction(imageTile, src)
          }
        })
      })

      var view = new View({
        center: [0, 0],
        zoom: 2,
        projection: projection,
        extent: [-180.0,-90.0,180.0,90.0]
      });
      var scaleLineControl = new ScaleLine({
        //设置比例尺单位，degrees、imperial、us、nautical、metric（度量单位）
        units: "metric"
      });
      map = new Map({
        logo:false,
        interactions: defaultInteractions({
          pinchRotate: false,
          mouseWheelZoom:false,
          doubleClickZoom:false,
          shiftDragZoom:false,
          dragPan:false
        }),
        controls: defaults({attribution: false,zoom:false}).extend([
          // new MousePosition(),
          scaleLineControl,
          new FullScreen()
        ]),
        layers: [layer1],
        target: 'myMap',
        view: view
      });
      this.bgLayer=layer1
      map.getView().fit([119.6636833624323, 31.33182968686947,120.12129162382348, 31.77128060702411], map.getSize());
      this.map=map
      this.$store.state.map=map
      map.on('singleclick', function(e){
        console.log(e.coordinate)
      })
    },
    initMapForArcgis() {
      console.log("开始加载地图！")
      let that=this
      var map=null
      var scaleLineControl = new ScaleLine({bar: true, text: true, minWidth: 125});
      // 地图坐标
      var projection = get('EPSG:4326');
      // 基础地图服务切片地址
      var tileUrl = "http://58.216.48.11:6080/arcgis/rest/services/CZ_Vector/MapServer/tile/{z}/{y}/{x}";
      // 坐标原点
      var origin = [-180.0, 90.0];
      // 分辨率
      var resolutions = [1.406250026231578,0.703125013115789,0.3515625065578945,0.17578125327894775,0.08789062663947399,0.043945313319736994,0.021972656659868472,0.010986328329934226,0.005493164164967124,0.0027465820824835504,0.0013732910412417797,6.866455206208899E-4,3.433227603104438E-4,1.716613801552224E-4,8.583069007761132E-5,4.291534503880566E-5,2.1457672519402802E-5,1.0728836259701401E-5,5.364418129850712E-6,2.682209064925356E-6,1.341104532462678E-6];
      //地图范围
      var fullExtent = [118.7320967970221,31.107756812535424,120.60430413298437,32.107465751900804];
      // var fullExtent = [-180.0,-90.0,180.0,90.0];
      var tileGrid = new TileGrid({
        tileSize: 256,
        origin: origin,
        extent: fullExtent,
        resolutions: resolutions
      });
      // 瓦片数据源
      var tileArcGISXYZ = new XYZ({
        tileGrid: tileGrid,
        projection: projection,
        url: tileUrl,
        tileLoadFunction: function (imageTile, src) {
          that.myTileLoadFunction(imageTile, src)
        }
      });
      var layer1=new Tile({
        source: tileArcGISXYZ
      })

      var map = new Map({
        target: 'myMap',
        logo:false,
        interactions: defaultInteractions({
          pinchRotate: false,
          // mouseWheelZoom:false,
          doubleClickZoom:false,
          shiftDragZoom:false,
          // dragPan:false
        }),
        controls: defaults({attribution: false,zoom:false}).extend([
          // new MousePosition(),
          scaleLineControl,
          new FullScreen()
        ]),
        layers: [
          layer1
        ],
        view: new View({
          //初始化中心点坐标
          center: [119.6680, 31.3175],
          resolutions: resolutions,
          // 注意：此处指定缩放级别不能通过zoom来指定，指定了也无效，必须通过resolution来指定
          resolution: 6.866455206208899E-4,
          projection: projection,
          extent: fullExtent
        })
      })
      this.bgLayer=layer1
      this.map=map
      this.$store.state.map=map
      map.on('singleclick', function(e){
        console.log(e.coordinate)
      })
    },

    myTileLoadFunction(imageTile, src){
      let img = new Image();
      img.crossOrigin = '';
      img.onload = function () {
        let canvas = document.createElement('canvas');
        let w = img.width;
        let h = img.height;
        canvas.width = w;
        canvas.height = h;
        let context = canvas.getContext('2d');
        context.drawImage(img, 0, 0, w, h, 0, 0, w, h);
        let imageData = context.getImageData(0, 0, w, h);
        for(let i = 0; i<imageData.height; i++){
          for(let j = 0; j<imageData.width; j++){
            var x = (i*4) * imageData.width + (j*4);
            var r = imageData.data[x];
            var g = imageData.data[x+1];
            var b = imageData.data[x+2];
            //运用图像学公式，设置灰度值
            var grey = r * 0.3 + g * 0.59 + b * 0.11;
            //将rgb的值替换为灰度值
            imageData.data[x] = grey;
            imageData.data[x+1] = grey;
            imageData.data[x+2] = grey;

            //基于灰色，设置为蓝色，这几个数值是我自己试出来的，可以根据需求调整
            imageData.data[x] = 55 - imageData.data[x];
            imageData.data[x+1] = 255 - imageData.data[x+1];
            imageData.data[x+2] = 305 - imageData.data[x+2];
            // imageData.data[x] = imageData.data[x+1] = imageData.data[x+2] = (r+g+b) / 7;
          }
        }
        context.putImageData(imageData, 0, 0);
        imageTile.getImage().src = canvas.toDataURL('image/png');
      }
      img.src = src;
    },
    message(text) {
      this.$Message({
        text: text,
        type: 'warning'
      })
    },

  },
};
</script>
<style lang='scss' scoped>
.centermap {
  margin-bottom: 30px;

  .maptitle {
    height: 60px;
    display: flex;
    justify-content: center;
    padding-top: 10px;
    box-sizing: border-box;

    .titletext {
      font-size: 28px;
      font-weight: 900;
      letter-spacing: 6px;
      background: linear-gradient(92deg,
          #0072ff 0%,
          #00eaff 48.8525390625%,
          #01aaff 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      margin: 0 10px;
    }

    .zuo,
    .you {
      background-size: 100% 100%;
      width: 29px;
      height: 20px;
      margin-top: 8px;
    }

    .zuo {
      background: url("../../assets/img/xiezuo.png") no-repeat;
    }

    .you {
      background: url("../../assets/img/xieyou.png") no-repeat;
    }
  }

  .mapwrap {

    height: 500px;
    width: 100%;
    // padding: 0 0 10px 0;
    box-sizing: border-box;
    position: relative;
    .map-container{
      width: 96%;
      height: 92%;
      margin-top: 3%;
      margin-left: 2%;
      padding: 0;
      display: flex;
      flex-direction: row;
      position: absolute;
    }
    .ansexi{
      position: absolute;
      left: 20px;
      top: -46px;
      width: 105px;
      height: 28px;
      border: 1px solid #00eded;
      border-radius: 10px;
      color: #00f7f6;
      text-align: center;
      line-height: 26px;
      letter-spacing: 6px;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5),
      0 0 6px rgba(0, 237, 237, 0.4);
    }
    .quanguo {
      position: absolute;
      right: 20px;
      top: -46px;
      width: 105px;
      height: 28px;
      border: 1px solid #00eded;
      border-radius: 10px;
      color: #00f7f6;
      text-align: center;
      line-height: 26px;
      letter-spacing: 6px;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5),
      0 0 6px rgba(0, 237, 237, 0.4);
    }
  }
}
</style>
